<template>
  <div class="manage">
    <el-table
      style="width: 100%"
      ref='multipleTable'
      @row-click="handleCurrentChange"
      @selection-change="selection"
      highlight-current-row
      :header-cell-style="{ backgroundColor: '#eaecf1', color: '#003d74' }"
      :row-style="rowstyles"
      :data="tableData.filter((data) => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="id" prop="id" width="100"> </el-table-column>
      <el-table-column label="姓名" prop="name"> </el-table-column>
      <el-table-column label="权限" prop="power"> </el-table-column>
      <el-table-column label="职位" prop="work"> </el-table-column>
      <el-table-column label="日期" prop="date"> </el-table-column>
      <el-table-column label="地址" prop="address"> </el-table-column>
      <el-table-column align="right">
        <template slot="header">
          <el-input v-model="search" @input="searchinput" size="mini" placeholder="输入关键字搜索" />
        </template>
        <template slot-scope="scope">
          <el-button size="mini" class="botton_xiu" @click="handleUpdata(scope.$index, scope.row)">修改</el-button>
            <el-dialog :visible.sync="alter_data" width="60%">
              <div style="text-align:left;width:85%;margin: 20px auto;font-size:23px">修改数据信息</div>
              <el-form :model="alterData" status-icon :rules="rule_s" ref="alterData" label-width="100px" class="demo-ruleForm">
                <el-form-item label="id" prop="id" v-show="false">
                  <el-input type="text" v-model="alterData.id" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="管理员姓名" prop="addname" >
                <el-input type="text" v-model="alterData.addname" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="管理员账号" prop="addusername" >
                <el-input type="text" v-model="alterData.addusername" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="管理员密码" prop="addpass">
                <el-input type="password" v-model="alterData.addpass" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="管理员权限" prop="power" style="text-align:left">
                <el-radio-group v-model="alterData.power" size="medium">
                  <el-radio border label="1"></el-radio>
                  <el-radio border label="2"></el-radio>
                  <el-radio border label="3"></el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="管理员工作" prop="work" style="text-align:left">
                <el-radio-group v-model="alterData.work" size="medium">
                  <el-radio border label="运维"></el-radio>
                  <el-radio border label="运维主管"></el-radio>
                  <el-radio border label="项目经理"></el-radio>
                  <el-radio border label="架构师"></el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="管理员地址" prop="address">
                <el-input type="text" v-model="alterData.address" autocomplete="off"></el-input>
              </el-form-item>
              <span>
                <el-button @click="alter_data = false">取 消</el-button>
                <el-button type="primary" @click="alterForm('alterData')">修 改</el-button>
              </span>
            </el-form>
          </el-dialog>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="text-align: center;position: absolute;bottom:2%;left:50%;transform: translateX(-50%);"
      background
      :hide-on-single-page="hidden_one"
      layout="prev, pager, next"
      :page-size="page_number"
      @current-change="clickPage"
      :total="allpage_number"
    >
    </el-pagination>
    <el-button
        class="someDelete"
        size="mini"
        type="danger"
        @click="someDelete"
        >批量删除
    </el-button>
    <el-button
        class="add"
        type="danger"
        @click="addManage=true"
        >添加管理员
    </el-button>

    <el-dialog :visible.sync="addManage" width="50%">
      <div style="text-align:left;width:85%;margin: 20px auto;font-size:23px">添加管理员</div>
      <el-form :model="ruleData" status-icon :rules="rule_s" ref="ruleData" label-width="100px" class="demo-ruleForm">
        <el-form-item label="管理员姓名" prop="addname" >
          <el-input type="text" v-model="ruleData.addname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="管理员账号" prop="addusername" >
          <el-input type="text" v-model="ruleData.addusername" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="管理员密码" prop="addpass">
          <el-input type="password" v-model="ruleData.addpass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="管理员权限" prop="power" style="text-align:left">
          <el-radio-group v-model="ruleData.power" size="medium">
            <el-radio border label="1"></el-radio>
            <el-radio border label="2"></el-radio>
            <el-radio border label="3"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="管理员工作" prop="work" style="text-align:left">
          <el-radio-group v-model="ruleData.work" size="medium">
            <el-radio border label="运维"></el-radio>
            <el-radio border label="运维主管"></el-radio>
            <el-radio border label="项目经理"></el-radio>
            <el-radio border label="架构师"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="管理员地址" prop="address">
          <el-input type="text" v-model="ruleData.address" autocomplete="off"></el-input>
        </el-form-item>
        <span>
          <el-button @click="addManage = false">取 消</el-button>
          <el-button type="primary" @click="addForm('ruleData')">添 加</el-button>
        </span>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [],
      search: "",
      currentRow: null,
      hidden_one: false,
      allpage_number: 9,
      page_number: 0,
      page_index: 1,
      userPower:0,
      multipleSelection: [],
      alter_data:false,
      addManage:false,
      ruleData: {
        addname: '',
        addusername: '',
        addpass: '',
        power: '',
        work: '',
        address: '',
      },
      alterData: {
        id:'',
        addname: '',
        addusername: '',
        addpass: '',
        power: '',
        work: '',
        address: '',
      },
      rule_s: {
        addname: [
            { required: true, message: '请输入管理员姓名', trigger: 'blur' },
            { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' }
          ],
        addusername: [
            { required: true, message: '请输入管理员账号', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
        addpass: [
        { required: true, message: '请输入管理员密码', trigger: 'blur' },
            { min: 10, max: 15, message: '长度在 10 到 15 个字符', trigger: 'blur' }
          ],
        power: [
            { required: true, message: '请选择账号权限', trigger: 'change'  }
        ],
        work: [
            {  required: true, message: '请选择账号职位', trigger: 'change'  }
        ],
        address: [
          { required: true, message: '请输入管理员地址', trigger: 'blur' },
          { min: 2, max: 25, message: '长度在 2 到 25 个字符', trigger: 'blur' }
        ],
      },
    };
  },
  methods: {
    rowstyles({ row, rowIndex }) {  //每行样式
      let aa = {
        "background-color": "#eaecf1",
        "color": "#000000",
      };
      return aa;
    },
    handleCurrentChange(row) {  //点击勾选或取消
      for(let i=0;i<this.tableData.length;i++){
        if(row.id==this.tableData[i].id){
            this.$refs.multipleTable.toggleRowSelection(this.tableData[i]);
        }
      }
    },
    searchinput(){  //查询方法，循环判断查询
        clearInterval(this.setInter)
        setInterval(()=>{
          //延迟查询

        },500)
    },
    selection(res){ //勾选状态每次改变时触发，存储勾选那一行的数据
      let arr=[]
      for(let i=0;i<res.length;i++){
        arr.push(res[i].id)
      }
      console.log(res,arr)
      this.multipleSelection=arr
    },
    handleDelete(index,value) { //单独删除后刷新一遍
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let type_,msg
            this.$axios.post("api/manageDelete?id="+value.id).then(async (data)=>{
              if(await data.data.code==-1) {
                type_="error"
              }else if(data.data.code==0){
                type_="warning"
              }else if(data.data.code==1){
                type_="success"
              }
              console.log(this.page_index)
              this.$axios.post(`api/managePage?page=${this.page_index}&number=${this.page_number}`).then( async (data)=>{
                this.tableData=await data.data
              }).catch(function (error) {
                console.log(error);
              });
              msg=await data.data.msg
              this.$message({
                type: type_,
                message: msg
              });
            }).catch(function (error) {
              console.log(error);
            });       
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    handleUpdata(index,value){  //点击修改后触发弹窗
      this.alter_data=true
      console.log(value)
      this.alterData.addpass=value.userPass
      this.alterData.addusername=value.userName
      this.alterData.addname=value.name
      this.alterData.work=value.work
      this.alterData.power=(value.power).toString()
      this.alterData.id=value.id
      this.alterData.address=value.address
    },
    alterForm: async function (formName){  //单独修改后刷新一遍
      this.$refs[formName].validate((valid)=>{
        if (valid) {
          const arr=JSON.stringify({id:this.alterData.id,name:this.alterData.addname,userName:this.alterData.addusername,userPass:this.alterData.addpass,
            power:this.alterData.power,work:this.alterData.work,address:this.alterData.address,userPower:this.userPower})
          //向后端请求修改
          let type_,msg
            this.$axios.post("api/manageUpdate",arr).then(async (data)=>{
              if(await data.data.code==-1) {
                type_="error"
              }else if(data.data.code==0){
                type_="warning"
              }else if(data.data.code==1){
                type_="success"
              }
              this.$axios.post(`api/managePage?page=${this.page_index}&number=${this.page_number}`).then( async (data)=>{
                this.tableData=await data.data
              }).catch(function (error) {
                console.log(error);
              });
              msg=await data.data.msg
              this.alter_data = false
              this.$message({
                type: type_,
                message: msg
              });
            }).catch(function (error) {
              console.log(error);
            });          
        } else {
          console.log('error submit!!');
          // return false
        }
      })
    },
    someDelete() {  //批量删除后刷新一遍
      //获取批量删除的数据
      console.log(this.multipleSelection)
      if(this.multipleSelection==""){
        this.$message({
            type: 'error',
            message: '没有选中任何选项'
          });
      }else {
        this.$confirm('此操作将删除多条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //向后端请求批量删除
          let type_,msg
          this.$axios.post("api/manageSomeDelete?id="+this.multipleSelection).then(async (data)=>{
              if(await data.data.code==-1) {
                type_="error"
              }else if(data.data.code==0){
                type_="warning"
              }else if(data.data.code==1){
                type_="success"
              }
              this.$axios.post(`api/managePage?page=${this.page_index}&number=${this.page_number}`).then( async (data)=>{
                this.tableData=await data.data
              }).catch(function (error) {
                console.log(error);
              });
              msg=await data.data.msg
              this.$message({
                type: type_,
                message: msg
              });
            }).catch(function (error) {
              console.log(error);
            });       
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      }
    },
    addForm(formName){  //添加管理员的方法
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const arr={name:this.ruleData.addname,userName:this.ruleData.addusername,userPass:this.ruleData.addpass,
            power:this.ruleData.power,work:this.ruleData.work,address:this.ruleData.address,userPower:this.userPower}
          //向后端请求添加用户
          console.log(arr);
          let type_,msg
          this.$axios.post("api/manageAdd",JSON.stringify(arr)).then(async (data)=>{
              if(await data.data.code==-1) {
                type_="error"
              }else if(data.data.code==0){
                type_="warning"
              }else if(data.data.code==1){
                type_="success"
              }
              this.$axios.post(`api/managePage?page=${this.page_index}&number=${this.page_number}`).then( async (data)=>{
                this.tableData=await data.data
              }).catch(function (error) {
                console.log(error);
              });
              msg=await data.data.msg
              this.addManage = false
              console.log(type_,msg)
              this.$message({
                type: type_,
                message: msg
              });
            }).catch(function (error) {
              console.log(error);
            });
        } else {
          console.log('error submit!!');
          // return false
        }
      })
    },
    clickPage(page){  //点击页数时
      this.page_index=page

      this.$axios.post(`api/managePage?page=${page}&number=${this.page_number}`).then((data)=>{
        console.log(data);
      this.tableData=data.data
      }).catch(function (error) {
        console.log(error);
      });
    }
  },
  mounted() {
    // <!--      数据根据高度穿多少数据，留空给分页         -->
    const hh = window.innerHeight;
    const ww = window.innerWidth;
    let number; //页面每页可传递多少条数据
    number = Math.floor((hh - 154) /60);
    this.page_number=number
    this.$axios.post(`api/manage`).then((data)=>{
      this.allpage_number=data.data.count
    }).catch(function (error) {
      console.log(error);
    });

    this.userPower=JSON.parse(localStorage.getItem("login")).power

    this.$axios.post(`api/managePage?page=1&number=${number}`).then((data)=>{
      this.tableData=data.data
    }).catch(function (error) {
      console.log(error);
    });

  },
};
</script>

<style lang="scss" scopted>

.manage {
  overflow-y: scroll;
  height: 94vh;
  &::-webkit-scrollbar {
    display: none;
    width: 0;
    height: 0;
    color: transparent;
  }

}

.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
  background: #5aa4ae !important;
  font-weight: bold;
  color: white;
}
.el-table__body tr.current-row > td.el-table__cell {
  background: #5aa4ae !important;
  font-weight: bold;
  color: white;
}
.botton_xiu {
  background: #003d74;
  color: white;
  border: 0;
  &:hover {
    background: #0157a1;
  }
}
.el-button {
  padding: 10px 18px;
  margin: 0 10px;
}
.someDelete{
  z-index: 30;
  padding: 9px 50px;
  font-size: 15px;
  right: 5%;
  position: absolute;
  bottom:2%;
}
.add {
  border: 0;
  z-index: 30;
  padding: 9px 50px;
  font-size: 15px;
  right: calc(10% + 130px);
  background: #5aa4ae;
  position: absolute;
  bottom:2%;
  &:hover {
    background: #0157a1;
  }
  &:focus {
    background: #0157a1;
  }
}
.demo-ruleForm {
  text-align: center;
}
.cell {
  overflow: hidden;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  box-orient: vertical;
  display: -webkit-box;
  display: box;
}
</style>